package com.xayy.core.utils;

import cn.kawins.base.utils.CollUtil;
import com.xayy.core.model.Page;

import java.util.List;

/**
 * @author Nie
 * @version V1.0
 * @date 2023/9/18 11:31
 */
public class PageHelper<T> {
    private List<T> data;
    private int pageSize;

    public PageHelper(List<T> data, int pageSize) {
        this.data = data;
        this.pageSize = pageSize;
    }

    /**
     * Get the page for the given page number.
     *
     * @param pageNumber the page number
     * @return the page
     */
    public Page<T> getPage(int pageNumber) {
        int totalElements = data.size();
        int totalPages = (int) Math.ceil((double) totalElements / pageSize);

        List<T> content = null;
        if (pageNumber > 0 && pageNumber <= totalPages) {
            int fromIndex = (pageNumber - 1) * pageSize;
            int toIndex = Math.min(fromIndex + pageSize, totalElements);
            content = data.subList(fromIndex, toIndex);
        }

        return new Page<T>(content, totalElements, totalPages, pageNumber, pageSize, CollUtil.newArrayList());
    }
}
